package com.zhihaoliang.coroutine.buss.excep.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.*

/**
 * @author 支豪亮
 * @date 2022/10/28 15:34
 * @des 通过 CoroutineExceptionHandler 捕获异常
 */
object ExceptionHandler {
    private val handler = CoroutineExceptionHandler { _, exception ->
        log("CoroutineExceptionHandler got $exception")
    }

    fun handlerException(mainScope:CoroutineScope) = mainScope.launch {
        val deferred = GlobalScope.async(handler) { // root coroutine with async
            log("Throwing exception from async")
            throw ArithmeticException() // Nothing is printed, relying on user to call await
        }
        try {
            deferred.await()
            log("Unreached")
        } catch (e: ArithmeticException) {
            log("Caught ArithmeticException")
        }

        val job = try {
            GlobalScope.launch(handler) { // root coroutine with launch
                log("Throwing exception from launch")
                throw IndexOutOfBoundsException() // Will be printed to the console by Thread.defaultUncaughtExceptionHandler
            }
        }catch(e:Exception) {
            log("Throwing exception from launch")
            null
        }

        job?.join()
        log("Joined failed job")
    }
}